package com.wswy.wyjk.ui.practiceNew;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.PagerSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.my.httpapi.api.annotation.ViewL;
import com.my.httpapi.api.baseUtils.LogUtils;
import com.my.httpapi.api.baseUtils.Toast;
import com.my.httpapi.api.baseView.BaseActivity;
import com.tencent.mmkv.MMKV;
import com.wswy.wyjk.AppContext;
import com.wswy.wyjk.R;
import com.wswy.wyjk.api.Api;
import com.wswy.wyjk.api.MMKVConstant;
import com.wswy.wyjk.api.entity.RequestParameter;
import com.wswy.wyjk.core.App;
import com.wswy.wyjk.model.PracticeData;
import com.wswy.wyjk.model.PracticeType;
import com.wswy.wyjk.ui.main.model.ErrResponse;
import com.wswy.wyjk.ui.main.model.PracticeModel;
import com.wswy.wyjk.ui.practiceNew.Adapter.PracticeAdapter;
import com.wswy.wyjk.ui.practiceNew.Adapter.TIMUChooseAdapter;
import com.wswy.wyjk.ui.practiceNew.Dialog.CustomDialog;
import com.wswy.wyjk.ui.practiceNew.event.PracticeEvent;
import com.wswy.wyjk.ui.practiceNew.event.UpdateErrCountEvent;
import com.wswy.wyjk.ui.share.ShareDialog;
import com.wswy.wyjk.ui.uitls.PracticeTypeUtils;
import com.wswy.wyjk.ui.widget.TipsChooserLayout;
import com.wswy.wyjk.utils.AdverConfigUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import kotlin.Unit;
import kotlin.jvm.functions.Function1;

@ViewL(R.layout.activity_practice)
public class PracticeNewActivity extends BaseActivity {
    private RecyclerView recyclerView;
    private TextView tvOrderIndex, tvRightCount, tvWrongCount, tvT, tvCollection;
    private TextView tvCurrPosition, tvDialogRightCount, tvDialogWrongCount;
    private ImageView imgBack;
    private TipsChooserLayout tipsChooserLayout;
    private PracticeAdapter practiceAdapter;
    private List<PracticeData> practiceList;
    private int localPotoon = 0;
    private PagerSnapHelper pagerSnapHelper;
    private LinearLayoutManager mLinearLayoutManager;
    private int rightCount, wrongCount;
    private int type;//1-顺序练习  2-未做练习   3-随机练习    4-章节练习  5-考试答错练习查看  6-难题攻克  7-错题练习
    private TIMUChooseAdapter timuChooseAdapter;
    private BottomSheetDialog dialog;
    private int correctNum = 1;
    private String typeName;
    private List<String> listCollction=new ArrayList<>();
    private int qId;
    private boolean isCollction;
    private   String token;
    private ViewGroup container;
    private  UnifiedBannerController unifiedBannerController;


    @Override
    protected void initData(Bundle savedInstanceState) {
        initView();
        initData();
        initListener();
    }

    @Override
    protected String showTitle() {
        return null;
    }

    @Override
    protected boolean statusBarIsBlack() {
        return true;
    }

    @Override
    protected void destroy() {
        EventBus.getDefault().unregister(this);
        //保存顺序练习当前的position
        if (type == 1) {
            MMKV.defaultMMKV().encode(MMKVConstant.POSITION, localPotoon);
        }
        unifiedBannerController.onDestroy();
    }

    private void initView() {
        tipsChooserLayout = findViewById(R.id.ll_practice_mode2);
        recyclerView = findViewById(R.id.recyclerView);
        imgBack = findViewById(R.id.img_back);
        tvOrderIndex = findViewById(R.id.tv_order_index);
        tvRightCount = findViewById(R.id.tv_right_count);
        tvWrongCount = findViewById(R.id.tv_wrong_count);
        tvT = findViewById(R.id.tv_t);
        tvCollection = findViewById(R.id.tv_collection);
        container=findViewById(R.id.banner_container);
    }

    private void initData() {
        token = MMKV.defaultMMKV().decodeString(MMKVConstant.TOKEN);
        if(TextUtils.isEmpty(token)){
            tvCollection.setVisibility(View.GONE);
        }
        correctNum = MMKV.defaultMMKV().decodeInt(MMKVConstant.ERRCOUNT, 1);
        type = getIntent().getIntExtra("type", 1);
        typeName = getIntent().getStringExtra("typeName");
        EventBus.getDefault().register(this);
        mLinearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        practiceAdapter = new PracticeAdapter(type);
        recyclerView.setLayoutManager(mLinearLayoutManager);
        recyclerView.setAdapter(practiceAdapter);

        if (type == 1) {
            tvT.setText("顺序练习");
            practiceList = App.getDaoSession().findAllPractice(PracticeTypeUtils.getPracticeType());
            for (int i = 0; i < practiceList.size(); i++) {
                if (!TextUtils.isEmpty(practiceList.get(i).isDo())) {
                    PracticeData practiceData = practiceList.get(i);
                    practiceData.setDoIt(Integer.valueOf(practiceList.get(i).isDo()));
                    practiceList.set(i, practiceData);
                }
            }
            localPotoon = MMKV.defaultMMKV().decodeInt(MMKVConstant.POSITION, localPotoon);
            if (localPotoon > 0) {
                recyclerView.scrollToPosition(localPotoon);
            }
        } else if (type == 2) {
            tvT.setText("未做练习");
            practiceList = App.getDaoSession().findAllPractice(PracticeTypeUtils.getPracticeType(PracticeType.TYPE_UNDONE));
        } else if (type == 3) {
            tvT.setText("随机练习");
            practiceList = App.getDaoSession().findAllPractice(PracticeTypeUtils.getPracticeType(PracticeType.TYPE_RANDOM));
        } else if (type == 4) {
            tvT.setText("章节练习");
            long chapterId = getIntent().getLongExtra("chapterId", -1);
            practiceList = App.getDaoSession().findAllPractice(PracticeTypeUtils.getPracticeType(PracticeType.TYPE_CHAPTER, chapterId));
        } else if (type == 5) {
            tvT.setText("答错题目");
            practiceList = ExamActivity.practiceErrList;
        } else if (type == 6) {
            tvT.setText("难题攻克");
            practiceList = App.getDaoSession().findAllPractice(PracticeTypeUtils.getPracticeType(PracticeType.TYPE_DIFFICULTY));
        } else if (type == 7) {
            tvT.setText(typeName + "练习");
            String sql = getIntent().getStringExtra("sql");
            practiceList = App.getDaoSession().findAllPractice(PracticeTypeUtils.getPracticeType(PracticeType.TYPE_ERROR, sql));
            noErroList();
        }
        practiceAdapter.setNewData(practiceList);
        pagerSnapHelper = new PagerSnapHelper();
        pagerSnapHelper.attachToRecyclerView(recyclerView);
        updateSubscript();
        initBottomSheetDialog();
        if (type == 1)
            showCount();
        //收藏功能
        tvCollection.setOnClickListener(view -> {
            if (isCollction) {
                //取消收藏
                Map<String, String> map = new HashMap<>();
                map.put("qid", qId + "");
                subscribe(Api.getApi().favoritesCancel(RequestParameter.generate().getSingedParams(map)),
                        request(data -> {
                            isCollction = false;
                            tvCollection.setCompoundDrawablesWithIntrinsicBounds(R.drawable.icon_topic_no_c, 0, 0, 0);
                            EventBus.getDefault().post(new UpdateErrCountEvent());
                        }, true));
            } else {
                Map<String, String> map = new HashMap<>();
                map.put("qid", qId + "");
                subscribe(Api.getApi().favoritesAdd(RequestParameter.generate().getSingedParams(map)),
                        request(data -> {
                            isCollction = true;
                            tvCollection.setCompoundDrawablesWithIntrinsicBounds(R.drawable.icon_topic_c, 0, 0, 0);
                            EventBus.getDefault().post(new UpdateErrCountEvent());
                        }, true));
            }
        });
        getCollect();
        //显示广告
        unifiedBannerController=new UnifiedBannerController(this,container,AdverConfigUtil.questionADPOSTID, AdverConfigUtil.isShowQuestionAD);
    }

    private void initListener() {
        imgBack.setOnClickListener(view -> finish());
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                localPotoon = recyclerView.getChildAdapterPosition(pagerSnapHelper.findSnapView(mLinearLayoutManager));
                updateSubscript();
                getClloction();
            }
        });

//        tvPrevPractice.setOnClickListener(view -> {
//            if (localPotoon == 0) return;
//            recyclerView.smoothScrollToPosition(--localPotoon);
//        });
//
//        tvNextPractice.setOnClickListener(view -> {
//            if (localPotoon == practiceList.size() - 1) {
//                new CustomDialog.Builder(PracticeNewActivity.this).setTitle("这是最后一道题是否返回首题").setNegativeButtonText("留在这里")
//                        .setPositiveButton("返回首题", (dialog, which) -> {
//                            localPotoon = 0;
//                            recyclerView.scrollToPosition(localPotoon);
//                            updateSubscript();
//                        }).create().show();
//                return;
//            }
//            recyclerView.smoothScrollToPosition(++localPotoon);
//        });

        tipsChooserLayout.setChooserCallback(new Function1() {

            @Override
            public Object invoke(Object o) {
                this.invoke(((Number) o).intValue());
                return Unit.INSTANCE;
            }

            public final void invoke(int it) {
                switch (it) {
                    case 0:
                        practiceAdapter.setMode(1);
                        break;
                    case 1:
                        practiceAdapter.setMode(2);
                }
                practiceAdapter.notifyDataSetChanged();
            }
        });

        tvOrderIndex.setOnClickListener(view -> {
            if (dialog != null) {
                dialog.show();
            }
        });
    }

    private void initBottomSheetDialog() {
        dialog = new BottomSheetDialog(this, R.style.BottomSheetDialog);
        View dialogView = LayoutInflater.from(this)
                .inflate(R.layout.layout_dialog_choose_timu, null);
        RecyclerView rv_1 = dialogView.findViewById(R.id.rv_1);
        GridLayoutManager mLinearLayoutManager1 = new GridLayoutManager(this, 6, GridLayoutManager.VERTICAL, false);
        timuChooseAdapter = new TIMUChooseAdapter();
        rv_1.setLayoutManager(mLinearLayoutManager1);
        rv_1.setAdapter(timuChooseAdapter);
        timuChooseAdapter.setNewData(practiceList);
        tvCurrPosition = dialogView.findViewById(R.id.tv_curr_position);
        tvDialogRightCount = dialogView.findViewById(R.id.tv_dialog_right_count);
        tvDialogWrongCount = dialogView.findViewById(R.id.tv_dialog_wrong_count);
        tvCurrPosition.setText((localPotoon + 1) + "/" + practiceList.size());
        timuChooseAdapter.setOnItemClickListener((adapter, view, position) -> {
            recyclerView.scrollToPosition(position);
            localPotoon = position;
            updateSubscript();
            getClloction();
            dialog.dismiss();
        });
        dialog.setContentView(dialogView);
    }

    private void updateSubscript() {
        int firstPosition = localPotoon + 1;
        int endPosition = practiceList.size();
        if (firstPosition > endPosition) {
            firstPosition = endPosition;
        }
        tvOrderIndex.setText(firstPosition + "/" + endPosition);
        if (tvCurrPosition != null)
            tvCurrPosition.setText(firstPosition + "/" + endPosition);
    }

    private void showCount() {
        rightCount = App.getDaoSession().countRight(PracticeTypeUtils.getPracticeType());
        wrongCount = App.getDaoSession().countErr(PracticeTypeUtils.getPracticeType());
        tvRightCount.setText("" + rightCount);
        tvWrongCount.setText("" + wrongCount);
        tvDialogRightCount.setText(tvRightCount.getText().toString());
        tvDialogWrongCount.setText(tvWrongCount.getText().toString());
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void practiceEvent(PracticeEvent practiceEvent) {
        if (practiceEvent.isRight()) {
            recyclerView.smoothScrollToPosition(++localPotoon);
            tvRightCount.setText("" + ++rightCount);
            tvDialogRightCount.setText(tvRightCount.getText().toString());
            App.getDaoSession().upDateData(practiceEvent.getId(), 1, practiceEvent.getMyAnswer());
            PracticeData practiceData=  practiceAdapter.getData().get(practiceEvent.getPosition());
            practiceData.setDo("1");
            practiceData.setDoA(practiceEvent.getMyAnswer()+"");
            practiceAdapter.getData().set(practiceEvent.getPosition(),practiceData);
            if (type == 7) {
                //通知错题本页面
                EventBus.getDefault().post(new UpdateErrCountEvent());
            }
        } else {
//            if (type != 7) {
//                PracticeType practiceType = PracticeTypeUtils.getPracticeType(PracticeType.TYPE_ERROR);
//                App.getDaoSession().AddErrData(practiceEvent.getId(), practiceType.licenseType.getTypeName(), Integer.valueOf(practiceType.subjectType.getTypeName()));
//            }
            tvWrongCount.setText("" + ++wrongCount);
            tvDialogWrongCount.setText(tvWrongCount.getText().toString());
            App.getDaoSession().upDateData(practiceEvent.getId(), 2, practiceEvent.getMyAnswer());
            PracticeData practiceData=  practiceAdapter.getData().get(practiceEvent.getPosition());
            practiceData.setDo("2");
            practiceData.setDoA(practiceEvent.getMyAnswer()+"");
            practiceAdapter.getData().set(practiceEvent.getPosition(),practiceData);
        }
        //上传题目
        uplaodTitle(practiceEvent.getId(), practiceEvent.isRight());
    }

    private void noErroList() {
        if (practiceList.size() == 0) {
            new CustomDialog.Builder(PracticeNewActivity.this).setTitle("暂无" + typeName).setNegativeButtonText("留在这里")
                    .setPositiveButton("关闭", (dialog1, which1) -> {
                        finish();
                    }).create().show();
        }
    }

    private void uplaodTitle(int id, boolean isRight) {
        String token = MMKV.defaultMMKV().decodeString(MMKVConstant.TOKEN);
        if (TextUtils.isEmpty(token)) {
            return;
        }
        Map<String, String> map = new HashMap<>();
        map.put("qid", id + "");
        map.put("correctNum", correctNum + "");
        if (isRight) {
            map.put("result", "1");
        } else {
            map.put("result", "0");
        }
        subscribe(Api.getApi().uploadErr(RequestParameter.generate().getSingedParams(map)),
                request(data -> {

                }, false));
    }

    private void getCollect() {
        if(TextUtils.isEmpty(token)){
            return;
        }
        subscribe(Api.getApi().favoritesList(RequestParameter.generate().getSingedParams()),
                request(data -> {
                    ErrResponse errResponse = (ErrResponse) data;
                    listCollction = errResponse.getTotal().getList();
                    if (practiceList.size() > 0) {
                        getClloction();
                    }
                }, false));
    }

    private boolean isClloction(int id) {
        for (int i = 0; i < listCollction.size(); i++) {
            if (id == Integer.valueOf(listCollction.get(i))) {
                return true;
            }
        }
        return false;
    }

    private void getClloction() {
        if(TextUtils.isEmpty(token))return;
        qId = practiceList.get(localPotoon).getId();
        isCollction = isClloction(qId);
        if (isCollction) {
            tvCollection.setCompoundDrawablesWithIntrinsicBounds(R.drawable.icon_topic_c, 0, 0, 0);
        } else {
            tvCollection.setCompoundDrawablesWithIntrinsicBounds(R.drawable.icon_topic_no_c, 0, 0, 0);
        }
    }
}
